
class Emitter {
    constructor() {
        this.events = {}
    }
    on(event, callback) {
        this.events[event].push(callback);
        return this // 可以用来链式调用
    }
    emit(...args) {
        let event = args[0];
        let params = [].slice.call(args, 1)
        this.events[event].forEach(fn => fn(params))
    }
    off(event, callback) {
        this.events[event].filter(fn => fn !== callback)
    }
    once(event, callback) {
        function wrapFunc(...args) {
            this.off(event, wrapFunc)
            callback.call(this, args)
        }
        this.on(event, wrapFunc)
    }
}


// 限制最大监听数量
class Emitter {
    constructor(maxListeners) {
        this.events = {}
        this.maxListeners = maxListeners || Infinity; // 无穷大不做限制
    }
    on(event, callback) {
        if (this.maxListeners !== Infinity && this.events[event].length >= this.maxListeners) {
            console.warn("多了")
            return this
        }
        this.events[event].push(callback);
        return this // 可以用来链式调用
    }
    emit(...args) {
        let event = args[0];
        let params = [].slice.call(args, 1)
        this.events[event].forEach(fn => fn(params))
    }
    off(event, callback) {
        this.events[event].filter(fn => fn !== callback)
    }
    once(event, callback) {
        function wrapFunc(...args) {
            this.off(event, wrapFunc)
            callback.call(this, args)
        }
        this.on(event, wrapFunc)
    }
}